package com.woniuxy.gateway.config;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

//@Configuration
public class GatewayCorsConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter corsGlobalFilter() {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            // 关键修复：处理预检请求时添加完整CORS头部
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.getHeaders().set("Access-Control-Allow-Origin", "*");
                response.getHeaders().set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                response.getHeaders().set("Access-Control-Allow-Headers", "*");
                response.getHeaders().set("Access-Control-Max-Age", "3600"); // 添加缓存时间
                response.getHeaders().set("Access-Control-Expose-Headers", "*"); // 暴露所有头部
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }

            // 非OPTIONS请求添加CORS头部
            response.getHeaders().set("Access-Control-Allow-Origin", "*");
            response.getHeaders().set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.getHeaders().set("Access-Control-Expose-Headers", "*");
            response.getHeaders().set("Access-Control-Allow-Credentials", "true");

            return chain.filter(exchange);
        };
    }
}